<template>
  <el-dialog
    :title="addForm.id ? '编辑部门':'添加部门'"
    :visible="visible"
    width="50%"
    @close="onDialogClose"
  >
    <el-form ref="ruleForm" :rules="rules" :model="addForm" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="addForm.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="addForm.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="addForm.manager" placeholder="请选择" @focus="getDeptsManager">
          <!-- label显示的数据 -->
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.username"
            :value="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="addForm.introduce" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="$emit('input', false)">取 消</el-button>
      <el-button type="primary" @click="onSave">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  getDepartments,
  addDepartments,
  getDepartmentsById,
  editDepartmentsById
} from '@/api/departments.js'
import { getEmployeesSimple } from '@/api/employees.js'
export default {
  name: 'AddDept',
  model: {
    // 默认value
    prop: 'visible'
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    treeData: {
      type: Object,
      required: true
    }
  },
  data() {
    // 部门名称验证
    const validateName = async(rule, value, callback) => {
      let flag = false
      if (this.addForm.id) {
        // ^编辑
        // 获取所有的部门
        const res = await getDepartments()
        // 筛选同级部门是否有重名
        const newArr = res.depts.filter(
          item => item.pid === this.treeData.pid && item.id !== this.treeData.id
        )
        flag = newArr.some(item => item.name === value)
      } else {
        // ^添加
        if (!this.treeData.children) return callback()
        flag = this.treeData.children.some(item => item.name === value)
      }
      if (flag) {
        callback(new Error('部门名称不能为' + value))
      } else {
        callback()
      }
    }
    // 部门编码的校验
    const validateCode = async(rule, value, callback) => {
      const res = await getDepartments()
      // console.log(res)
      let flag = false
      if (this.addForm.id) {
        // ^编辑
        const newArr = res.depts.filter(
          item => item.cord !== this.treeData.cord
        )
        flag = newArr.some(item => item.code === value)
      } else {
        // ^添加
        flag = res.depts.some(item => item.code === value)
      }
      if (flag) {
        return callback(new Error('部门编码不能为' + value))
      }
      callback()
    }

    return {
      // 提交的数据
      addForm: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          },
          { validator: validateName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur'
          },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请输入部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ]
      },
      options: [],
      value: ''
    }
  },
  created() {},
  methods: {
    // 对话框关闭
    onDialogClose() {
      // 子传父，关闭弹出框
      this.$emit('input', false)
      // 重置表单
      this.$refs.ruleForm.resetFields()
      // 因为编辑部门的时候,addForm中有很多数据了，单靠this.$refs.ruleForm.resetFields()无法全部重置，需要手动去赋值
      this.addForm = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    // 获取部门负责人
    async getDeptsManager() {
      const res = await getEmployeesSimple()
      // console.log(res)
      this.options = res
    },
    // 确定表单
    async onSave() {
      try {
        // 若不传入回调函数，则会返回一个 promises ,所以需要await
        await this.$refs.ruleForm.validate()
        if (this.addForm.id) {
          // ^编辑
          await editDepartmentsById(this.addForm)
          this.$emit('success-edit')
          this.$message.success('修改部门成功')
        } else {
          // ^添加
          this.addForm.pid = this.treeData.id
          // 新增加部门
          await addDepartments(this.addForm)
          this.$message.success('添加部门成功')
          this.$emit('success-add')
        }
        // 调用弹出框关闭事件
        this.onDialogClose()
      } catch (err) {
        console.log(err)
      }
    },
    // 获取最新的数据
    async getNewData(id) {
      // console.log('最新的数据' + id)
      // 根据id ,查询部门详情
      const res = await getDepartmentsById(id)
      this.addForm = res
    }
  }
}
</script>

<style lang='less' scoped>
</style>
